﻿using CoreShop.App.Units.Interface;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Model.FromBody;
using CoreShop.Model.FromBody;
using CoreShop.Model.UI;
using CoreShop.Services;
using FastMember;
using Loading;
using MySqlX.XDevAPI.Relational;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using Org.BouncyCastle.Ocsp;
using SqlSugar.Extensions;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Security.Cryptography;
using System.Speech.Synthesis.TtsEngine;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using WebKit;
using static CoreShop.Library.GlobalEnumVars;
using static NPOI.HSSF.Util.HSSFColor;
using static System.Windows.Forms.AxHost;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace CoreShop.App
{
    public partial class FrmUserRegister : UIForm
    {
        public bool returnValue;
        OpaqueCommand cmd1 = new OpaqueCommand();
        OpaqueCommand cmd2 = new OpaqueCommand();
        public corecmsuser member = new corecmsuser();        
        List<VipGrantCartModel> VipGrantCartList = new List<VipGrantCartModel>();
        public FrmUserRegister(corecmsuser _member,string code)
        {
            InitializeComponent();
            member = _member;
            mobile.TextBox.GotFocus += mobile_GotFocus;
            txtPwd.TextBox.GotFocus += mobile_GotFocus;
            txtPwd2.TextBox.GotFocus += mobile_GotFocus;
            if (string.IsNullOrEmpty(member.mobile)) member.mobile = code;
            //pnl_level.Enabled = false;
            txtPwd.Focus();
        }

        private void mobile_GotFocus(object sender, System.EventArgs e)
        {
            numKeybord.SetTextBox((UIEdit)sender, UITextBox.UIEditType.String, 0);
        }

        public FrmUserRegister(string code)
        {
            InitializeComponent();
            mobile.TextBox.GotFocus += mobile_GotFocus;
            txtPwd.TextBox.GotFocus += mobile_GotFocus;
            txtPwd2.TextBox.GotFocus += mobile_GotFocus;
            if (string.IsNullOrEmpty(member.mobile)) member.mobile = code;
        }

        private void FrmEditInputs_Load(object sender, EventArgs e)
        {            

        }
        private void BindComboBoxData()
        {
            try
            {
                #region 加载性别信息
                this.sex.Items.Clear();
                var memberSex = EnumHelper.EnumToList<GlobalEnumVars.Sex>();
                sex.DataSource = memberSex;
                sex.DisplayMember = "description";
                sex.ValueMember = "value";
                if (memberSex.Count > 0) this.sex.SelectedIndex = 0;
                #endregion

                #region 加载推荐人信息
                this.parentId.Items.Clear();
                //List<corecmsuser> parentGrid = new corecmsuserServices().SelectByCorpId(GlobalConstVars.sysUser.corpId, GlobalConstVars.sysUser.storeId);
                List<corecmsuser> parentGrid = new corecmsuserServices().QueryAsync(0);
                this.parentId.DataSource = parentGrid;
                this.parentId.DisplayMember = "userName";
                this.parentId.ValueMember = "id";
                if (parentGrid.Count > 0) this.parentId.SelectedIndex = 0;
                #endregion

                LoadVipLevelAsync();
                LoadVipCardType();
            }
            catch (Exception)
            {
                throw;
            }
        }

        public bool IsPwdIsOK()
        {
            string pwd1 = this.txtPwd.Text.Trim();
            string pwd2 = this.txtPwd2.Text.Trim();
            if (!string.IsNullOrEmpty(pwd1) && !string.IsNullOrEmpty(pwd2))
            {
                if (pwd2 != pwd1)
                {
                    UIMessageBox.Show("两次输入的密码不同，请重新输入");
                    this.txtPwd.Focus();
                    return false;
                }
            }
            else if (!string.IsNullOrEmpty(pwd1) && string.IsNullOrEmpty(pwd2))
            {
                UIMessageBox.Show("两次输入的密码不同，请重新输入");
                this.txtPwd2.Focus();
                return false;
            }
            else if (string.IsNullOrEmpty(pwd1) && !string.IsNullOrEmpty(pwd2))
            {
                UIMessageBox.Show("两次输入的密码不同，请重新输入");
                this.txtPwd.Focus();
                return false;
            }
            else if (!string.IsNullOrEmpty(pwd1) && !string.IsNullOrEmpty(pwd2))
            {
                if (pwd2 == pwd1) return true;
            }
            else if (string.IsNullOrEmpty(pwd1) && string.IsNullOrEmpty(pwd2))
                return true;
            return true;
        }

        private async Task<bool> GiveGenerateCard()
        {
            try
            {
                cmd1.ShowOpaqueLayer(pnl_Form, 125, true);
                VipSendCardDto info = new VipSendCardDto();
                info.vipTel = member.mobile;
                info.vipId = member.id;
                info.branchId = AppConstVars.sysStore.branchId;
                info.cardTypeId = CommFunc.ConvertToString(mbtCardType.SelectedButtonsValues[0]);
                info.vipBirthday = birthday.Text;
                info.password = txtPwd.Text;
                info.cardNo = txtCardNo.Text;
                var resultCard = await MemberApiUtil.GiveGenerateCard(info);
                if (resultCard == null) return false;
                return true;
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message);
                return false;  
            }
            finally { cmd1.HideOpaqueLayer(); }

        }

        private async void btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                if (!CheckData1()) return;

                if (member.id > 0)
                {
                    if (!await GiveGenerateCard())
                    {
                        UIMessageBox.Show("发卡失败:。", "系统提示", UIStyle.Orange, UIMessageBoxButtons.OK);
                        return;//会员发卡
                    }
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;                    
                }
                else 
                    RegisterMember();
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private async void RegisterMember()
        {
            try
            {
                //先注册
                var vipInfo = new VipGenerateCardDto()
                {
                    vipTel = mobile.Text.Trim(),
                    vipNo = mobile.Text.Trim(),
                    branchId = AppConstVars.sysStore.branchId,
                    vipBirthday = birthday.Text,
                    vipName = userName.Text,
                    vipSix = CommFunc.ConvertToInt32(sex.SelectedValue),
                    vipCardTypeId = 0,
                    vipLevelId = CommFunc.ConvertToInt64(this.cmbLevelType.SelectedValue),
                };

                //先注册
                try
                {
                    cmd1.ShowOpaqueLayer(pnl_Form, 125, true);
                    var rs = await MemberApiUtil.RegisterVip(vipInfo);
                    if (rs == null)
                    {
                        UIMessageBox.Show("注册失败:。", "系统提示", UIStyle.Orange, UIMessageBoxButtons.OK);
                        return;
                    }
                    if (rs.code != 200)
                    {
                        UIMessageBox.Show("注册失败:。" + rs.msg, "系统提示", UIStyle.Orange, UIMessageBoxButtons.OK);
                        return;
                    }

                    //注册储值卡
                    if (mbtCardType.SelectedButtons.Count() > 0)
                    {
                        vipInfo.vipCardTypeId = mbtCardType.SelectedButtonsValues[0];
                        if (string.IsNullOrEmpty(txtCardNo.Text))
                        {
                            rs = await MemberApiUtil.GiveGenerateCardNew(vipInfo);
                        }
                        else
                        {
                            GsPosVip posVip0 = JsonConvert.DeserializeObject<GsPosVip>(rs.data.ToString());
                            if (posVip0 == null)
                            {
                                UIMessageBox.Show("注册失败:。" + rs.msg, "系统提示", UIStyle.Orange, UIMessageBoxButtons.OK);
                                return;
                            }
                            member.mobile = posVip0.vipTel;
                            member.id = CommFunc.ConvertToInt64(posVip0.vipId);
                            if (!await GiveGenerateCard()) return;
                        }
                    }
                    
                    if (rs == null) return;
                    if (rs.code != 200)
                    {
                        UIMessageBox.Show("发卡失败:。" + rs.msg, "系统提示", UIStyle.Orange, UIMessageBoxButtons.OK);
                        return;
                    }
                    string dataStr = rs.data.ToString();
                    GsPosVip posVip = JsonConvert.DeserializeObject<GsPosVip>(rs.data.ToString());
                    if (posVip != null)
                    {
                        member = ModelHelper.VipToMember(posVip, AppConstVars.sysStore);
                        if (member != null) new MemberUtil().SaveUserInfo(member);
                        ShowSuccessTip("保存成功");
                        this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    }
                    else
                    {
                        UIMessageBox.Show("读取会员卡失败:。" + rs.msg, "系统提示", UIStyle.Orange, UIMessageBoxButtons.OK);
                    }
                }
                catch (Exception ex)
                {
                }
                finally { cmd1.HideOpaqueLayer(); }

            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private bool CheckData1()
        {
            if (mobile.Text == null || mobile.Text == "")
            {
                UIMessageBox.Show("请输入电话号码", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                return false;
            }
            if (string.IsNullOrEmpty(userName.Text))
            {
                userName.Text = mobile.Text;
                //UIMessageBox.Show("请输入姓名", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                //return false;
            }
            if (CommFunc.ConvertToInt64(this.cmbLevelType.SelectedValue) == 0)
            {
                UIMessageBox.Show("会员等级未选择，请选择", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                return false;
            }
            if (string.IsNullOrEmpty(txtCardNo.Text)) return IsPwdIsOK();
            return true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void grade_SelectedValueChanged(object sender, EventArgs e)
        {
            //Int64 id = CommFunc.ConvertToInt64(grade.SelectedValue);
            //var gradeModel = gradeGrid.Find(p => p.id == id);
            //if (gradeModel != null) discount.Text = gradeModel.discountValue.ToString() + "%";
        }

        
        public async void LoadVipLevelAsync()
        {
            try
            {
                cmd1.ShowOpaqueLayer(pnl_level, 125, true);
                var rs = await MemberApiUtil.GetVipLevelAsync();
                if (rs.code != 200)
                {
                    ShowSuccessTip("获取等级失败:。" + rs.msg);
                    return;
                }
                List<VipLevelMode> levelListAll = JsonConvert.DeserializeObject<List<VipLevelMode>>(rs.data.ToString());
                var levelList = levelListAll.Where(p=>p.enable == false).ToList();
                this.cmbLevelType.Items.Clear();
                cmbLevelType.DataSource = levelList;
                cmbLevelType.DisplayMember = "levelName";
                cmbLevelType.ValueMember = "levelId";
                if (levelList.Count > 0)
                {
                    var levelItem = levelList.First();
                    cmbLevelType.SelectedValue = levelItem.levelId;
                    cmbLevelType.Text = levelItem.levelName;
                }                    
            }
            catch (Exception ex)
            {
                ShowSuccessTip("获取等级失败:。" + ex.Message);
            }
            finally
            {
                cmd1.HideOpaqueLayer();
            }
        }              

        public async void LoadVipCardType()
        {
            try
            {
                cmd1.ShowOpaqueLayer(mbtCardType, 125, true);
                var rs = await MemberApiUtil.GetVipCardType();
                if (rs.code != 200)
                {
                    //HideWaitForm();
                    ShowSuccessTip("获取卡类型失败:。" + rs.msg);
                    return;
                }
                List<VipGrantCartModel> listAll = JsonConvert.DeserializeObject<List<VipGrantCartModel>>(rs.data.ToString());
                VipGrantCartList = listAll.Where(p => p.enable == false && p.posCard == false).ToList();
                
                AddCartItems(VipGrantCartList);
            }
            catch (Exception ex)
            {
                //HideWaitForm();
                ShowSuccessTip("获取卡类型失败:。" + ex.Message);
            }
            finally { cmd1.HideOpaqueLayer(); }
        }
        public void AddCartItems(List<VipGrantCartModel> items, VipRechargeCardModel cardModel = null)
        {
            this.Invoke(new Action(() =>
            {
                string sName = "";
                mbtCardType.Clear();
                mbtCardType.TagString = "会员卡类型";
                mbtCardType.AutoWidth = false;
                mbtCardType.ItemSize = new Size(130, 40);
                mbtCardType.MaxSelected = 1;                
                bool isSelected = cardModel == null ? true : false;                
                foreach (var item in items)
                {
                    sName = item.cardTypeName;
                    if ((cardModel != null) && (cardModel.cardTypeId == item.cardTypeId))
                        isSelected = true;
                    mbtCardType.Add(sName, item.cardTypeId.ToLong(), isSelected);
                    isSelected = false;
                }
            }));            
        }

        private void numKeybord_OKButtonClick(object sender, string text, int intvalue, double doublevalue)
        {
            btnOk_Click(null, null);
        }

        private void FrmUserRegister_Shown(object sender, EventArgs e)
        {
            BindComboBoxData();
            ControlsDataBinding.DataBind(member, this, DataSourceUpdateMode.OnPropertyChanged);
            try
            {
                if (member.id <= 0)
                {
                    parentId.Text = "";
                    parentId.SelectedValue = 0;
                }
                else
                {
                    corecmsusercategory memberCategory = new corecmsusercategoryServices().GetById(member.userCategoryId);                    
                    sex.Text = EnumHelper.GetEnumByValue<GlobalEnumVars.Sex>(member.sex.ObjToInt(0));
                    corecmsuser parentGrade = new corecmsuserServices().GetById(member.parentId);
                    if (parentGrade != null) parentId.Text = parentGrade.userName;

                    if (member.userWx > 0)
                    {
                        //this.userWx.ReadOnly = true;
                    }
                }
                mobile.Focus();
                mobile.SelectAll();
            }
            catch { }
        }

        private async void btnGetCode_Click(object sender, EventArgs e)
        {
            string cardNumber = "";
            var frm = new frmInputNumber(0, "储值卡号输入");
            frm.IsNumber = false;
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                cardNumber = frm.txtNumber.Text;
            }
            frm.Dispose();
            if (string.IsNullOrEmpty(cardNumber)) return;
            
            try
            {
                cmd1.ShowOpaqueLayer(pnl_cardtype, 125, true);
                var cardModel = await MemberApiUtil.GetCardByCardNo(cardNumber);
                if (cardModel == null) return;
                txtCardNo.Text = cardModel.cardNo;
                txtAmount.Text = cardModel.sumBalance.ToString("0.00#");
                AddCartItems(VipGrantCartList, cardModel);
                mobile.Focus();
            }
            catch (Exception ex)
            {
                //HideWaitForm();
                ShowSuccessTip("获取卡类型失败:。" + ex.Message);
            }
            finally { cmd1.HideOpaqueLayer(); }
        }
    }
}